package cn.spiral.complain.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.spiral.complain.dao.ComplainDao;
import cn.spiral.complain.entity.Complain;
import cn.spiral.complain.service.ComplainService;
import cn.spiral.core.service.impl.BaseServiceImpl;
import cn.spiral.core.utils.QueryHelper;

@Service("complainService")
public class ComplainServiceImpl extends BaseServiceImpl<Complain> implements ComplainService {
	
	private ComplainDao complainDao;
	
	@Autowired
	public void setComplainDao(ComplainDao complainDao) {
		super.setBaseDao(complainDao);
		this.complainDao = complainDao;
	}

	@Override
	public void autoDeal() {

		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.DAY_OF_MONTH, 1);//设置当前时间的日期为1号
		cal.set(Calendar.HOUR_OF_DAY, 0);//设置当前时间的日期为1号,0时
		cal.set(Calendar.MINUTE, 0);//设置当前时间的日期为1号,0分
		cal.set(Calendar.SECOND, 0);//设置当前时间的日期为1号,0秒
		Date thisMonth=cal.getTime();
		cal.add(Calendar.MONTH, -1);//设置当前时间为上个月月初
		Date preMonth=cal.getTime();
		
		//查询本月之前的待受理的投诉列表
		QueryHelper queryHelper = new QueryHelper(Complain.class, "c");
		queryHelper.addCondition("c.state=?", Complain.COMPLAIN_STATE_UNDONE);
		queryHelper.addCondition("c.compTime >= ?", preMonth);//上月1号0时0分0秒
		queryHelper.addCondition("c.compTime < ?", thisMonth);//本月1号0时0分0秒
		
		List<Complain> list = complainDao.findObjects(queryHelper);
		if(list != null && list.size() > 0){
			//更新投诉信息的状态为 已失效
			for(Complain comp: list){
				comp.setState(Complain.COMPLAIN_STATE_INVALID);
				this.update(comp);
			}
		}
	}

	@Override
	public List<Map<String, Object>> getStatisDataByYear(int year) {
		List<Object[]> list=complainDao.getStatisDataByYear(year);
		List<Map<String, Object>> dataList=new ArrayList<Map<String,Object>>();
		int i=1;
		for (Object[] objects : list) {
			while(i<Integer.valueOf(objects[0].toString())){
				Map<String, Object> dataMap =new HashMap<String, Object>();
				dataMap.put("label", ""+i+"月");
				dataMap.put("value", 0);
				dataList.add(dataMap);
				i++;
			}
			Map<String, Object> dataMap =new HashMap<String, Object>();
			dataMap.put("label", ""+i+"月");
			dataMap.put("value", Integer.valueOf(objects[1].toString()));
			dataList.add(dataMap);
		}
		while(i<=12){
			Map<String, Object> dataMap =new HashMap<String, Object>();
			dataMap.put("label", ""+i+"月");
			dataMap.put("value", 0);
			dataList.add(dataMap);
			i++;
		}
		return dataList;
	}

}
